#!/bin/bash 
set -e

TMP=${TMP:-/tmp/work}
LOG=${LOG:-$HOME/logs/stage3}
SRC=${SRC:-/sources}

name=tcl
version=8.6.11

rm -rf $TMP
mkdir -p $TMP $LOG

tar xf $SRC/$name$version-src.tar.gz -C $TMP

{ time \
   {

    cd $TMP/$name$version

    tar -xf $SRC/tcl$version-html.tar.gz --strip-components=1

    SRCDIR=$(pwd)
    cd unix
    ./configure --prefix=/usr           \
                --mandir=/usr/share/man \
                $([ "$(uname -m)" = x86_64 ] && echo --enable-64bit)
    make

    sed -e "s|$SRCDIR/unix|/usr/lib|" \
        -e "s|$SRCDIR|/usr/include|"  \
        -i tclConfig.sh

    sed -e "s|$SRCDIR/unix/pkgs/tdbc1.1.2|/usr/lib/tdbc1.1.2|" \
        -e "s|$SRCDIR/pkgs/tdbc1.1.2/generic|/usr/include|"    \
        -e "s|$SRCDIR/pkgs/tdbc1.1.2/library|/usr/lib/tcl8.6|" \
        -e "s|$SRCDIR/pkgs/tdbc1.1.2|/usr/include|"            \
        -i pkgs/tdbc1.1.2/tdbcConfig.sh

    sed -e "s|$SRCDIR/unix/pkgs/itcl4.2.1|/usr/lib/itcl4.2.1|" \
        -e "s|$SRCDIR/pkgs/itcl4.2.1/generic|/usr/include|"    \
        -e "s|$SRCDIR/pkgs/itcl4.2.1|/usr/include|"            \
        -i pkgs/itcl4.2.1/itclConfig.sh

    unset SRCDIR

    make install

    chmod -v u+w /usr/lib/libtcl${version:0:3}.so

    make install-private-headers

    ln -sfv tclsh${version:0:3} /usr/bin/tclsh

    mv /usr/share/man/man3/{Thread,Tcl_Thread}.3

    }
} 2>&1 | tee $name.log
    
[ $PIPESTATUS = 0 ] && mv $name.log $LOG || exit $PIPESTATUS

rm -fr $TMP
